<template>
    <div class="page">
        <!-- <n-icon size="30" :component="CloudDownloadOutline" @click="loadPage" class="reflash" /> -->
        <n-icon size="30" :component="FileTrayFullOutline" @click="onEdit" class="edit" />
        <n-icon size="30" :component="CodeWorking" @click="onPopEdit(null)" class="tag-btn" />
        <n-icon size="27" :component="Reload" @click="onReload" class="reflash" />

        <div class="list">
            <div class="item" v-for="item in videoStore.list" :class="{ choose: selectVideos.includes(item) }" @click="onChoose($event, item)">
                <div class="img" @click.self="onPlay(item)" :style="{ backgroundImage: `url(${getImage(item)})` }">
                    <div class="time" v-if="item.duration">{{ formatDuratione(item.duration) }}</div>
                    <n-icon size="30" :component="ArrowDownCircle" @click.stop="onDownload(item)" class="down" :color="getColor(item)"></n-icon>
                    <n-icon size="80" :component="CaretForwardCircle" @click.stop="onPlay(item, true)" class="play" color="rgba(255, 0, 0, 0.64)"></n-icon>
                    <n-icon size="30" v-if="edit" :component="CloseCircleSharp" @click="onRemove(item)" class="close" color="#f00" />
                </div>
                <div class="info t1">
                    <span @click="onLoadVideo(item.src)">{{ videoStore.well ? videoStore.well_word : item.title }}</span>
                </div>
                <div class="info t2">
                    <span @click="onLoadPic(item.poster)">{{ formatTime(item.date) }}</span>
                    <n-icon size="20" :component="CodeWorking" @click="onPopEdit(item)" class="edit-btn" />
                </div>
                <!-- <div class="btns">
                    <n-button type="warning" @click="onRemove(item)" size="tiny">delete</n-button>
                </div> -->
                <div class="tags">
                    <n-tag size="small" closable v-for="i in item.tags" :key="i" @close="onRemoveTag(i, item)" @click="onClickTag(i)">{{ getTag(i) }}</n-tag>
                </div>
            </div>
        </div>
        <div class="j-page">
            <n-pagination :page-slot="7" @update:page="onPage" v-model:page="videoStore.page" :page-count="videoStore.totalPages" />
        </div>
    </div>
    <JTag :list="tagStore.list" @change="onChangeTags" :selected="selectTags"></JTag>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { NForm, NPagination, NIcon, NTreeSelect, NInput, NButton, NFormItem, NSpace, NTag, useMessage } from "naive-ui";
import { get, patch, post, remove } from "@/comm/request";
import { url_video } from "@/comm/api";
import { FileTrayFullOutline, CodeWorking, Reload, CloseCircleSharp, ArrowDownCircle, CaretForwardCircle } from "@vicons/ionicons5";

import { formatTimeAgo, formatDuratione } from "@/comm/format";
import { useTagStore } from "@/stores/tag";
import { usePopStore } from "@/stores/pop";
import { useVideoStore } from "@/stores/video";

import JTag from "@/components/j-tags/index.vue";
import { useLogStore } from "@/stores/log";
// const userStore = useUserStore();
const tagStore = useTagStore();
const popStore = usePopStore();
const videoStore = useVideoStore();
const message = useMessage();
const logStore = useLogStore();

const selectTags = ref([]);

onMounted(() => {
    tagStore.load();
});

// const well = ref(true);

// const poster = ref("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png");
// const title = ref("UI library for Grand Theft Auto");

const edit = ref(false);
const selectVideos = ref<any[]>([]);

onMounted(() => {
    loadPage();
});

const getTagById = (id: string) => {
    let item = tagStore.list.find(i => i._id == id);
    return item;
};

function onReload() {
    loadPage();
}

const getColor = (item: any) => {
    if (item.name) {
        return "#00ff00";
    }
    return "#ff0000";
};

const getTag = (id: string) => {
    let item = getTagById(id);
    if (item) {
        return item.name;
    }
    return "";
};

const onClickTag = (id: any) => {
    // let item = getTagById(id);
    // console.log(item);
    videoStore.resetTag(id);
};

const onChangeTags = (val: any) => {
    popStore.showTag(false);
    console.log(val);
    if (videoStore.cur) {
        videoStore.cur.tags = val;
        videoStore.update(videoStore.cur);
    } else {
        selectVideos.value.forEach(i => {
            i.tags = val;
            videoStore.update(i);
        });
        selectVideos.value = [];
        edit.value = false;
    }
};

const onPopEdit = (item: any) => {
    videoStore.cur = item;
    if (item) {
        selectTags.value = item.tags || [];
    } else {
        selectTags.value = [];
    }

    popStore.showTag(true);
};

const onLoadPic = (poster: string) => {
    console.log("load", poster);
    const link = "https://www.step2step.cn/mg/video/img";
    post(link, { poster }, true).then(async (res: any) => {
        console.log(res);
        if (res.data.name) {
            message.success("更新成功");
            loadPage();
        } else {
            message.warning("更新失败");
        }
    });
};

const onDownload = (item: any) => {
    let twitterUrl = "https://ssstwitter.com/?url=" + encodeURIComponent(item.src);
    // chrome.tabs.create({ url: twitterUrl });
    window.open(twitterUrl);
};

const onLoadVideo = (src: string) => {
    (window as any).chrome.runtime.sendMessage(src);
};

const getImage = (item: any) => {
    if (videoStore.well) {
        return videoStore.well_poster;
    }
    return "https://www.step2step.cn/proxy/images/" + item.pic;
};

const loadPage = async () => {
    videoStore.load();
    // let res: any = await get(url_video, { page: page.value, limit: limit.value });
    // console.log(res.data);
    // list.value = res.data.list;
    // list.value.forEach(element => {
    //     element.tags = ["a", "b", "c"];
    // });
    // totalPages.value = res.data.pagination.totalPages;
};

const onPage = (n: number) => {
    videoStore.page = n;
    setTimeout(() => {
        loadPage();
    }, 30);
};

const onRemoveTag = (n: any, item: any) => {
    console.log(n);
    item.tags = item.tags.filter((i:any) => i != n);
};

const onPlay = (item: any, local = false) => {
    console.log("play", item);
    logStore.addLog({ videoId: item._id });
    if (edit.value) return;
    if (!videoStore.well) {
        if (local) {
            window.open("https://www.step2step.cn/proxy/videos/" + item.name);
        } else {
            window.open(item.src);
        }
    }
};

const onRemove = async (item: any) => {
    await videoStore.remove(item._id);
    loadPage();
    // let res = await remove(url_video + "/" + item._id);
    // console.log(res);
    // loadPage();
};

const formatTime = (str: string) => {
    if (!str) return "未知时间";
    let t = new Date(str);
    let n = t.getTime();
    // console.log(t, n);
    return formatTimeAgo(n);
};

const onEdit = () => {
    edit.value = !edit.value;
    selectTags.value = [];
    selectVideos.value = [];
};

const onChoose = (e:any, item:any) => {
    if (!edit.value) return;
    console.log("choose", item);
    e.stopPropagation();
    e.preventDefault();
    if (selectVideos.value.includes(item)) {
        selectVideos.value = selectVideos.value.filter(i => i != item);
    } else {
        selectVideos.value.push(item);
    }
};
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
